package com.lynn.common.net.observer

import android.content.Context
import com.google.gson.Gson
import com.lynn.common.net.exception.ServerException
import java.lang.reflect.Type

/**
 * @description: 解析字符串为对象
 * @author: bailing
 * @datetime: 2025/6/6 14:06
 **/
abstract class EntityListObserver<T> : BaseObserver() {

    override fun onNext(t: String) {
        var s = t
        if (s.isEmpty()) {
            s = "[]"
        }
        if (s.startsWith("[") && s.endsWith("]")) {
            val listType = getDataType()
            onSuccess(Gson().fromJson(s, listType))

        } else {
            val t = ServerException(1000, "返回数据格式错误")
            onError(t)
        }
    }

    /**
     * val listType = object : TypeToken<List<Person>>() {}.type
     */
    abstract fun getDataType(): Type


    // 成功
    abstract fun onSuccess(t: T)
}